<template>
    <div>
        <div class="headline">账户管理</div>
        <div class="search">
            <div class="middle">
                <el-input v-model="input" placeholder="请输入账号名称" :suffix-icon="Search" size="default"
                    @input="handleSearch" />
            </div>
            <div class="middle">
                <el-button type="primary" size="default" @click="handleAdd">新增</el-button>
            </div>
        </div>
        <div class="table">
            <el-table :data="currentPageData" stripe border size="small">
                <el-table-column label="序号" align="center" width="50">
                    <template #default="data">
                        {{ (currentPage4 - 1) * pageSize4 + data.$index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column label="账号名称" align="center">
                    <template #default="data">{{ data.row.account }}</template>
                </el-table-column>
                <el-table-column label="账号头像" align="center">
                    <template #default="data">
                        <el-image v-if="data.row.img" :src="`${data.row.img}`"
                            :preview-src-list="[`${data.row.img}`]" alt="头像" preview-teleported />
                        <div v-else>暂无头像</div>
                    </template>
                </el-table-column>
                <el-table-column label="角色类型" align="center">
                    <template #default="data">
                        <div class="deta_tupe">
                            {{
                                data.row.type === 1 ? '超管' :
                                    data.row.type === 2 ? '劳务公司' :
                                        data.row.type === 3 ? '薪资审核员' :
                                            data.row.type === 4 ? '项目部' :
                                                '未知'
                            }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="角色名称" align="center">
                    <template #default="data">{{ data.row.name || '未知' }}</template>
                </el-table-column>
                <el-table-column label="账号状态" align="center">
                    <template #default="data">
                        <el-switch v-model="data.row.status" :active-value="1" :inactive-value="2" active-text="开启"
                            inactive-text="停用" inline-prompt @change="handleStatusChange(data.row)" />
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" align="center">
                    <template #default="data">{{ data.row.create_time || '未知' }}</template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template #default="data">
                        <el-button type="primary" @click="handleEdit(data.row)" class="delete-btn"
                            size="default">编辑</el-button>
                        <el-button type="danger" @click="handleDelete(data.row)" class="delete-btn"
                            v-show="data.row.id !== 1" size="default">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="page">
            <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4"
                :page-sizes="[10, 20, 50, 100, 200]" :background="true" layout="sizes, total, prev, pager, next, jumper"
                :total="filteredData.length" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
        <el-dialog v-model="dialogVisible" :title="dialogTitle" @close="resetForm" destroy-on-close
            style="width: 1000px; margin: 0 auto;">
            <el-form ref="addFormRef" :model="formData" :rules="formRules" label-width="100px">
                <el-form-item label="账户名称" prop="account" required>
                    <el-input v-model="formData.account" placeholder="请输入账户名称" maxlength="50" />
                </el-form-item>
                <el-form-item label="账户角色" prop="roleid" required>
                    <el-select v-model="formData.roleid" placeholder="请选择账户角色" clearable @change="handleRoleChange">
                        <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="账户密码" prop="password">
                    <el-input v-model="formData.password" type="password" placeholder="请输入账户密码"
                        @input="formData.password = formData.password.replace(/[^\d]/g, '')" />
                </el-form-item>

                <el-form-item label="确认密码" prop="confirmPassword" v-if="dialogTitle === '新增账户'">
                    <el-input v-model="formData.confirmPassword" type="password" placeholder="请再次输入密码"
                        @input="formData.confirmPassword = formData.confirmPassword.replace(/[^\d]/g, '')" />
                </el-form-item>
                <el-form-item label="账户头像" prop="img" required>
                    <el-upload class="avatar-uploader" :show-file-list="false" :http-request="handleCustomUpload">
                        <div class="avatar-upload-area">
                            <img v-if="formData.img" :src="`${formData.img}`" class="avatar-img" />
                            <div v-else class="avatar-placeholder">
                                <el-icon class="avatar-icon">
                                    <Plus />
                                </el-icon>
                            </div>
                        </div>
                    </el-upload>
                </el-form-item>
                <div class="fee-row" v-if="formData.type === 2">
                    <el-form-item label="管理费-长期" prop="manage_p"
                        :rules="[{ required: true, message: '请输入长期管理费', trigger: 'change' }]">
                        <el-input-number v-model="formData.manage_p" :min="0" size="small" controls-position="right" />
                    </el-form-item>
                    <el-form-item label="管理费-短期" prop="manage_l"
                        :rules="[{ required: true, message: '请输入短期管理费', trigger: 'change' }]">
                        <el-input-number v-model="formData.manage_l" :min="0" size="small" controls-position="right" />
                    </el-form-item>
                    <el-form-item label="管理费-学员" prop="manage_x"
                        :rules="[{ required: true, message: '请输入学员管理费', trigger: 'change' }]">
                        <el-input-number v-model="formData.manage_x" :min="0" size="small" controls-position="right" />
                    </el-form-item>
                </div>
                <el-form-item label="状态" prop="status" required>
                    <el-switch v-model="formData.status" :active-value="1" :inactive-value="2" active-text="开启"
                        inactive-text="停止" inline-prompt />
                </el-form-item>
                <el-form-item label="账户描述" prop="description">
                    <UEditor v-model="formData.description" placeholder="请输入账户描述内容" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
                <el-button @click="resetForm">取消</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue';
import UEditor from '/@/components/UEditor/index.vue';
import { accountApi, accountDeleteApi, accountDetailApi, accountAddEditApi } from '/@/api/permissions/index';
import { dataurl, pictureApi } from '/@/api/url/index'
import { ElMessage, ElForm, ElMessageBox } from 'element-plus'

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref('新增账户');

// 搜索框
const input = ref('')

// 表格数据类型定义
interface TableRow {
    id: number;
    account: string;
    img?: string;
    name?: string;
    status: number;
    create_time?: string;
    type: number;
    description?: string;
    manage_p?: number;
    manage_l?: number;
    manage_x?: number;
}
const tableData = ref<TableRow[]>([]); // 初始化为空数组，避免undefined

// 过滤后的数据
const filteredData = computed(() => {
    if (!tableData.value || tableData.value.length === 0) return [];
    if (!input.value.trim()) {
        return tableData.value;
    }
    const keyword = input.value.trim().toLowerCase();
    return tableData.value.filter(row =>
        row.account.toLowerCase().includes(keyword)
    );
});

// 角色数据类型定义
interface Role {
    id: number;
    name: string;
    type: number;
}
const roleList = ref<Role[]>([]);

// 表单数据
const formData = ref({
    id: 0,
    account: '',
    roleid: '',
    type: 0,
    password: '',
    img: '',
    status: 1,
    pid: 0,
    manage_p: 0,
    manage_l: 0,
    manage_x: 0,
    description: '',
    confirmPassword: ''
});

// 分页
const currentPage4 = ref(1);
const pageSize4 = ref(10);


// 表单引用
const addFormRef = ref<InstanceType<typeof ElForm>>();

// 验证规则
const formRules = computed(() => ({
    account: [
        { required: true, message: '请输入账户名称', trigger: 'change' }
    ],
    roleid: [
        { required: true, message: '请选择账户角色', trigger: 'change' }
    ],
    password: [
        {
            required: !formData.value.id, message: '请输入账户密码', trigger: 'change'
        }, 
        {
            pattern: /^\d+$/, message: '密码只能包含数字', trigger: 'change'
        },
        {
            min: 6, max: 20, message: '密码长度在 6-20 位之间', trigger: 'change'
        },
    ],
    confirmPassword: [
        {
            required: !formData.value.id, message: '请再次输入密码', trigger: 'change'
        },
        {
            pattern: /^\d+$/, message: '密码只能包含数字', trigger: 'change'
        },
        {
            min: 6, max: 20, message: '密码长度在 6-20 位之间', trigger: 'change'
        },
        {
            validator: (rule: any, value: string, callback: any) => {
                if (value !== formData.value.password) {
                    callback(new Error('两次密码输入不一致'));
                } else {
                    callback();
                }
            },
            trigger: ['blur', 'change']
        }
    ],
    status: [
        { required: true, message: '请选择账号状态', trigger: 'change' }
    ],
    img: [
        { required: true, message: '请上传账户头像', trigger: 'change' }
    ],
}));

// 分页数据
const currentPageData = computed(() => {
    if (!filteredData.value || filteredData.value.length === 0) return [];
    const start = (currentPage4.value - 1) * pageSize4.value;
    const end = start + pageSize4.value;
    return filteredData.value.slice(start, end);
});

// 分页事件
const handleSizeChange = (val: number) => {
    pageSize4.value = val;
    currentPage4.value = 1;
};

// 当前页码变化事件
const handleCurrentChange = (val: number) => {
    currentPage4.value = val;
};

// 搜索事件
const handleSearch = () => {
    currentPage4.value = 1;
};

// 获取账户列表
const getAccountList = () => {
    accountApi().signIn({})
        .then(res => {
            tableData.value = res.data || [];
            console.log(tableData.value);
            
        })
        .catch(err => {
            ElMessage.error('获取账户列表失败：' + (err.msg || '网络异常'));
        });
};
getAccountList();

// 获取角色列表
const getRoleList = () => {
    accountDetailApi().signIn({})
        .then(res => {
            roleList.value = res.data || [];
        })
        .catch(err => {
            console.error('获取角色列表失败：', err);
            ElMessage.error('获取角色列表失败：' + (err.msg || '网络异常'));
        });
};
getRoleList();

// 处理角色选择变化，更新表单的 type 字段
const handleRoleChange = (selectedRoleId: number) => {
    if (selectedRoleId) {
        const matchedRole = roleList.value.find(role => role.id === selectedRoleId);
        formData.value.type = matchedRole ? matchedRole.type : 0;
    } else {
        formData.value.type = 0;
    }
};
// 新增账户
const handleAdd = () => {
    dialogTitle.value = '新增账户';
    formData.value = {
        id: 0,
        account: '',
        roleid: '',
        type: 0,
        password: '',
        img: '',
        status: 1,
        pid: 0,
        manage_p: 0,
        manage_l: 0,
        manage_x: 0,
        description: '',
        confirmPassword: ''
    };
    dialogVisible.value = true;
};

// 编辑表单
const handleEdit = (row: TableRow) => {
    dialogTitle.value = '编辑账户';
    // 通过角色ID匹配
    const matchedRole = roleList.value.find(r => r.id === row.roleid)
        || roleList.value.find(r => r.type === row.type);
    formData.value = {
        id: row.id,
        account: row.account,
        roleid: matchedRole ? matchedRole.id : 0,
        type: matchedRole ? matchedRole.type : 0,
        password: '',
        img: row.img || '',
        status: row.status,
        pid: 0,
        manage_p: row.manage_p || 0,
        manage_l: row.manage_l || 0,
        manage_x: row.manage_x || 0,
        description: row.description || '',
        confirmPassword: ''
    };
    dialogVisible.value = true;
};
// 删除账户
const handleDelete = (row: TableRow) => {
    ElMessageBox.confirm(
        `确定要删除账号「${row.account}」吗？`,
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        accountDeleteApi().signIn({ id: row.id })
            .then(() => {
                ElMessage.success('删除成功');
                getAccountList();
            })
            .catch(err => {
                ElMessage.error('删除失败：' + (err.msg || '网络异常'));
            });
    }).catch(() => {
    });
};

// 上传图片
const handleCustomUpload = async (options: any) => {
    try {
        const file = Array.isArray(options.file) ? options.file[0] : options.file;
        const uploadFormData = new FormData();
        uploadFormData.append('file', file);
        const response = await pictureApi().signIn(uploadFormData);
        if (response.code === 1 || response.code === 200) {
            formData.value.img = response.url;
            addFormRef.value?.validateField('img');
            options.onSuccess(response);
            ElMessage.success('上传成功');
        } else {
            options.onError(response);
            ElMessage.error('上传失败：' + (response.msg || '未知错误'));
        }
    } catch (err: any) {
        options.onError(err);
        ElMessage.error('上传失败：' + (err.msg || '网络异常'));
    }
};
// 提交表单
const handleSubmit = () => {
    addFormRef.value?.validate((isValid) => {
        if (!isValid) {
            ElMessage.warning('请完善表单必填项');
            return;
        }
        accountAddEditApi().signIn({ ...formData.value })
            .then((response) => {
                ElMessage.success(dialogTitle.value === '新增账户' ? '添加成功' : '编辑成功');
                dialogVisible.value = false;
                getAccountList();
            })
            .catch(err => {
                console.error('API 错误：', err);
                ElMessage.error((dialogTitle.value === '新增账户' ? '添加' : '编辑') + '失败：' + (err.msg || '网络异常'));
            });
    });
};

// 重置表单
const resetForm = () => {
    if (addFormRef.value) {
        addFormRef.value.resetFields();
        addFormRef.value.clearValidate();
    }
    formData.value.type = '';
    dialogVisible.value = false;
};

// 账号状态变更
const handleStatusChange = (row: TableRow) => {
    const statusText = row.status === 1 ? '开启' : '停用';
    const updateData = { ...row, status: row.status };
    accountAddEditApi().signIn(updateData)
        .then(() => {
            ElMessage.success(`账号已${statusText}`);
            getAccountList();
        })
        .catch(err => {
            ElMessage.error(`更新为${statusText}失败：` + (err.msg || '网络异常'));
            row.status = row.status === 1 ? 2 : 1; // 回滚状态
        });
};
</script>

<style scoped>
.headline {
    font-size: 18px;
    margin-bottom: 20px;
    color: #303133;
}

.search {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
}

.middle:first-child {
    min-width: 300px;
}

.table {
    margin-top: 10px;
}

.table :deep(.el-image) {
    width: 45px;
    height: 45px;
    cursor: pointer;
}

.delete-btn {
    font-size: 12px;
    margin-right: 5px;
}

.page {
    display: flex;
    justify-content: space-evenly;
    margin-top: 16px;
    padding-right: 20px;
}

.deta_tupe {
    color: rgb(124, 153, 248);
    background-color: #ECF5FF;
    border-radius: 4px;
    border: 1px solid rgba(124, 153, 248, 0.3);
    padding: 5px 12px;
    text-align: center;
    font-size: 12px;
    max-width: 120px;
    display: inline-block;
}

.avatar-upload-area {
    width: 120px;
    height: 120px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: border-color 0.3s;
}

.avatar-upload-area:hover {
    border-color: #409eff;
}

.avatar-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 6px;
}

.avatar-placeholder {
    color: #666;
    text-align: center;
}

.avatar-icon {
    font-size: 24px;
}

:deep(.el-form-item) {
    margin-bottom: 18px;
}

.fee-row {
    display: flex;
    gap: 20px;
    align-items: center;
    flex-wrap: nowrap;
    margin-bottom: 18px;
}

.fee-row :deep(.el-form-item) {
    margin-bottom: 0 !important;
    flex: none;
}

.fee-row :deep(.el-input-number) {
    width: 160px;
}
</style>